<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  canvas {
    display: block;
    margin: 0 auto;
    border: 2px solid #aaa;
  }
</style>
<body>
  <canvas id="canvas" height="500px" width="500px">
    您的浏览器版本过低，请升级浏览器或者使用谷歌浏览器打开！
  </canvas>
  <script>
     /** @type {HTMLCanvasElement} */
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');

    // 画布宽高
    // var w=h=500;
    var w = 500;
    var h = 500;
    var x = 100;
    var y = 100;
    var r = 20;

    // 水平垂直速度
    var xSpeed = 2;
    var ySpeed = 3;

    setInterval(() => {
      // 清除画布
      ctx.clearRect(0, 0, w, h);
      /**
       * 在小球碰到边缘时，速度去相反即可
       */
      if (x - r <= 0 || x + r >= w ) {
        xSpeed = -xSpeed;
      }
      x = x - xSpeed;

      if (y - r <= 0 || y + r >= h ) {
        ySpeed = -ySpeed;
      }
      y = y - ySpeed;
      // 水平移动
      drawCircle(x, y, r);
    }, 10);

    function drawCircle(x, y, r) {
      ctx.beginPath();
      ctx.arc(x, y, r, 0, Math.PI * 2);
      ctx.fillStyle = 'gold';
      ctx.fill();
    }
</script>
  </script>
</body>
</html>